<?php
namespace App\Services\Api;

/**
 * 旧版服务号接口调用基类
 * @package App\Services\Api
 */
class SogalBaseService
{
    protected $baseUri;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->baseUri = config('url.old_wechat_api');
    }
    /**
     * 生成签名方法
     * @param $params
     * @return string
     */
    public function createSign($params){
        foreach ($params as &$v){
            $v=stripslashes($v);
        }
        unset($params['sig']);
        ksort($params);
        $secret = 'c&a&6&$2&';
        $sn=md5(urldecode(http_build_query($params)).$secret);
        return $sn;
    }

    /**
     * 接口请求
     * @param string $uri
     * @param array $query
     * @param $postParams
     * @param string $method
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function http($query = [], $postParams = [], $method = 'GET',$uri = 'index.php')
    {
        isset($query['apiKey']) || $query['apiKey'] = 'wechat_suofeiya_laravel';
        isset($query['timestamp']) || $query['timestamp'] = time();
        if ($method == 'GET'){
            isset($query['sig']) || $query['sig'] = $this->createSign($query);
        }elseif ($method == 'POST'){
            isset($query['sig']) || $query['sig'] = $this->createSign(array_merge($query, $postParams));
        }
        $client = new \GuzzleHttp\Client(['base_uri' => $this->baseUri]);
        $response = $client->request($method, $uri, [
            'query' => $query,
            'form_params' => $postParams,
        ]);
        $code = $response->getStatusCode(); // 200
        $reason = $response->getReasonPhrase(); // OK
        if ($code != 200) {
            throw new \Exception('请求出错:'. $reason);
        }
        $body = $response->getBody()->getContents();
        $res = json_decode($body, true);
        return $res;
    }
}